package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.*;

/**
 * Created by singerdreamer on 2018-04-17.
 */
public class Zuoye {
//767d963ed266459aa8bf32184599786d
//20aeba76c9234db7302dadf66f9ac1b
    public static void main(String args[]) {
        zuoye();
    }

    private static void zuoye() {
        System.out.println("111");
        String url = "http://repo.typesafe.com/typesafe/ivy-releases/org.scala-sbt/sbt-launch/";
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient client = HttpClients.createDefault();
             InputStream inputStream = null;
             CloseableHttpResponse response = client.execute(httpGet);) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String xmlResult = EntityUtils.toString(entity, "utf-8");
                //System.out.println("xmlResult = " + xmlResult);
                Document document = DocumentHelper.parseText(xmlResult);
                Element ele = document.getRootElement();
                Iterator iter = ele.elementIterator("body");
                List<String> urlList = new ArrayList<>();
                while (iter.hasNext()) {
                    Element recordEless = (Element) iter.next();
                    Iterator itersElIterator = recordEless.elementIterator("pre"); // 获取子节点body下的子节点form
                    // 遍历Header节点下的Response节点
                    while (itersElIterator.hasNext()) {
                        Element itemEle = (Element) itersElIterator.next();
                        String href = itemEle.elementTextTrim("a"); // 拿到body下的子节点form下的字节点banlce的值
                        urlList.add(href);
                    }
                }
                Collections.sort(urlList);
                String param = urlList.get(urlList.size() - 1);
                downLoadFromUrl(url + param + "sbt-launch.jar", "sbt-launch.jar", "C:/Users/singerdreamer/Desktop");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
        System.out.println("下载路径 = " + urlStr);
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3 * 1000);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        InputStream inputStream = conn.getInputStream();
        File saveDir = new File(savePath);
        FileOutputStream fos = null;
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        if(file.exists()){
            String md5Str1 = getFileMD5(inputStream);
            String md5Str2 = getFileMD5(file);
            System.out.println("md5Str1"+md5Str1);
            System.out.println("md5Str2"+md5Str2);
            if(md5Str1.equals(md5Str2)){
                System.out.println("已经存在该文件。。。。。");
            }
        }else{
            byte[] getData = readInputStream(inputStream);
            fos = new FileOutputStream(file);
            fos.write(getData);
        }
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("info:" + url + " download success");

    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        byte buffer[] = new byte[8192];
        int len;
        try (FileInputStream in = new FileInputStream(file);){
            digest = MessageDigest.getInstance("MD5");
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String getFileMD5(InputStream in) {
        MessageDigest digest = null;
        byte buffer[] = new byte[8192];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            while ((len = in.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}